﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Benchmark
{
	/// <summary>
	/// MSDN example to find the median in a LINQ collection.
	/// 
	/// Source: http://msdn.microsoft.com/en-us/library/cc981895(v=vs.100).aspx
	/// </summary>
	public static class LINQExtension
	{
		public static long Median(this IEnumerable<long> source)
		{
			if (source.Count() == 0)
				throw new InvalidOperationException("Cannot compute median for an empty set.");

			var sortedList = from number in source
							 orderby number
							 select number;

			int itemIndex = (int)sortedList.Count() / 2;

			if ((sortedList.Count() & 1) == 0)
				return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2;
			else
				return sortedList.ElementAt(itemIndex);
		}
	}
}
